Event Handling and Listener
Event Handling:
In Java, events are handled using the Delegation Event Model. This model clearly defines how an event is generated, delivered, and processed.
An event is an object that represents a change of state or user action.
Examples:
- Clicking a button
- Pressing a key
- Moving the mouse
- Submitting a form
- Creating a session (in web apps)
Event-driven model in Java
Java uses the Delegation Event Model, which has three main parts:
- Event Source
The object where the event occurs
(e.g., Button, TextField, ServletContext)
- Event Object
Contains information about the event
(e.g., ActionEvent, MouseEvent)
- Event Listener
An interface that receives and handles the event
(e.g., ActionListener, MouseListener)
In Java, listeners are objects that wait for and respond to events. They are a core part of event-driven programming, especially used in GUI applications, web applications, and frameworks like Swing, AWT, JavaFX, and Servlets.
Basic idea of a Listener
A listener:
- Listens for an event (like a button click, mouse movement, or request)
- Gets notified automatically when that event occurs
- Executes code in response to the event
In simple words:
Event happens -> Listener is notified -> Listener reacts
Listeners help to:
- Separate event handling logic from core application logic
- Make programs more interactive
- Follow loose coupling (event source doesn't need to know details of handler)
Java uses Delegation Event Model
- Event handling involves:
- Event Source
- Event Object
- Event Listener
- Events are handled by registering listeners
- Listener methods are automatically invoked